import axios from "axios"
import qs from 'qs'
import { useUserStore } from '@/store'
import router from '@/router'

const service = axios.create({
    baseURL: import.meta.env.VITE_BASE_API,
    timeout: 5000
})

// 请求拦截
service.interceptors.request.use(config => {
    const userStore = useUserStore()
    // 设置token
    config.headers.Authorization = userStore.token || ''
    return config
}, error => {
    return Promise.reject(error)
})

// 响应拦截
service.interceptors.response.use(response => {
    const { code, data, msg } = response.data
    if (code === 200) {
        return {
            msg,
            data
        }
    }
    // token过期,需要重新登录
    else if (code === 500 && msg === '未能读取到有效 token') {
        ElMessage.error('登录已过期,请重新登录!')
        const userStore = useUserStore()
        userStore.token = ''
        router.replace('/login')
        return Promise.reject(msg)
    }
    else {
        console.log(code, data, msg)
        // 自动导包了,不用管这里的警告
        ElMessage.error(msg)
        return Promise.reject(msg)
    }
}, error => {
    ElMessage.error(error.msg || '请求失败,请联系管理员!')
    return Promise.reject(error)
})

// 请求方法
const http = {
    post(url, params) {
        return service.post(url, params, {
            transformRequest: [(params) => {
                return JSON.stringify(params)
            }],
            headers: {
                'Content-Type': 'application/json'
            }
        })
    },
    put(url, params) {
        return service.put(url, params, {
            transformRequest: [(params) => {
                return JSON.stringify(params)
            }],
            headers: {
                'Content-Type': 'application/json'
            }
        })
    },
    get(url, params) {
        return service.get(url, {
            params,
            paramsSerializer: params => {
                return qs.stringify(params)
            }
        })
    },
    // parm => {id:10}
    // /api/user/10
    getRestApi(url, params) {
        let _params
        if (Object.is(params, undefined || null)) {
            _params = ''
        } else {
            _params = '/'
            for (const k in params) {
                if (params.hasOwnProperty(k) && params[k] != null && params[k] != undefined) {
                    _params += `${params[k]}/`
                }
            }
            // 去掉最后的/
            _params = _params.substring(0, _params.length - 1)
        }
        if (_params) {
            return service.get(`${url}${_params}`)
        } else {
            return service.get(url)
        }
    },
    delete(url, params) {
        let _params
        if (Object.is(params, undefined || null)) {
            _params = ''
        } else {
            _params = '/'
            for (const k in params) {
                if (params.hasOwnProperty(k) && params[k] != null && params[k] != undefined) {
                    _params += `${params[k]}/`
                }
            }
            // 去掉最后的/
            _params = _params.substring(0, _params.length - 1)
        }
        if (_params) {
            return service.delete(`${url}${_params}`)
        } else {
            return service.delete(url)
        }
    },
    upload(url, params) {
        return service.post(url, params, {
            headers: {
                'Conten-Type': 'multipart/form-data'
            }
        })
    }
}

export default http